﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace KjsyModUpdaterForWindows
{
    class Tools
    {
        /// <summary>
        /// 下载文件到流。
        /// </summary>
        /// <param name="remptepath">远程地址，一般就是服务器编号</param>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static MemoryStream Download(string remptepath, string filename)
        {
            HttpWebRequest request = WebRequest.Create(Program.URL + remptepath + filename) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            

            MemoryStream stream = new MemoryStream();
            byte[] bArr = new byte[2048];
            int size;
            do
            {
                size = responseStream.Read(bArr, 0, bArr.Length);
                stream.Write(bArr, 0, size);
            } while (size > 0);
            
            responseStream.Close();
            return stream;
        }

        /// <summary>
        /// 计算文件的hash值
        /// </summary>
        /// <param name="fs">该文件的文件流</param>
        /// <returns></returns>
        public static string GetHashCode(FileStream fs)
        {
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(fs);
                fs.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return "";
            }
        }


        public static ModInfo GetModInfo(LitJson.JsonData data)
        {
            try
            {
                return new ModInfo
                {
                    FileName = data["filename"].ToString(),
                    HashCode = data["hashcode"].ToString()
                };
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

        public static ModInfo GetModInfo(string data)
        {
            return new ModInfo
            {
                FileName = data.Split(';')[0],
                HashCode = data.Split(';')[1]
            };
        }
    }
}
